import 'package:flutter/material.dart';
import 'package:flutter_bsbdj/interfaces/view_interface.dart';
import 'package:flutter_bsbdj/pagers/news/new_info_detail.dart';
import 'package:flutter_bsbdj/utils/constant.dart';
import 'package:flutter_bsbdj/utils/http_util.dart';
import 'package:flutter_bsbdj/bean/newsinfo.dart';
import 'package:dio/dio.dart';
import 'package:flutter_bsbdj/utils/widget_views.dart';
import 'package:flutter_bsbdj/dialogs/big_image_dialog.dart';

class NewsIndex extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return NewsIndexWidget();
  }
}

class NewsIndexWidget extends State<NewsIndex> {
  int dataType = 0;
  NewsInfo newsInfo;
  PageController _pageController;
  ScrollController _scrollController = ScrollController();
  Map<int,List<NewContent>> allData={};
  String type="top";
  List<String> types=["top","shehui","guonei","guoji","yule","tiyu","junshi","keji","caijing","shishang"];

  Constant _constant;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _pageController=PageController(
      initialPage: dataType
    );
    _getNewsInfo();
    _constant=Constant.getInstance();
    ThemeEvent.getInstance().registerEvent(this);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Container(
        child: Column(
          children: <Widget>[
            _newsTitles(),
            Container(
              width: MediaQuery.of(context).size.width,
              height: 1,
              color: Colors.black54,
            ),
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(5)),
                ),
                width: MediaQuery.of(context).size.width,
                child: PageView.builder(
                  itemCount: 10,
                  itemBuilder: (context,index){
                    return newsPager(index);
                  },
                  controller: _pageController,
                  onPageChanged: (index) {
                    setState(() {
                      dataType = index;
                      type=types[index];
                      if (MediaQuery.of(context).size.width <
                          (dataType + 1) * 70.0) {
                        _scrollController.position.moveTo(
                            (dataType + 1) * 70.0 -
                                MediaQuery.of(context).size.width);
                      } else {
                        _scrollController.position.moveTo(0.0);
                      }
                      if(allData[index]==null){
                        _getNewsInfo();
                      }
                    });
                  },
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
  //新闻小标题部分
  Widget _newsTitles() {
    return Container(
      height: 50,
      child: ListView(
        controller: _scrollController,
        scrollDirection: Axis.horizontal,
        children: <Widget>[
          _titleTypes("头条", 0,"top"),
          _titleTypes("社会", 1,"shehui"),
          _titleTypes("国内", 2,"guonei"),
          _titleTypes("国际", 3,"guoji"),
          _titleTypes("娱乐", 4,"yule"),
          _titleTypes("体育", 5,"tiyu"),
          _titleTypes("军事", 6,"junshi"),
          _titleTypes("科技", 7,"keji"),
          _titleTypes("财经", 8,"caijing"),
          _titleTypes("时尚", 9,"shishang"),
        ],
      ),
    );
  }

  //标题的item
  Widget _titleTypes(String name, int index,String ctype) {
    return GestureDetector(
      child: Container(
        color: dataType == index ? Colors.grey : (_constant.getTheme()?Colors.white:Theme.of(context).primaryColor),
        width: 70,
        alignment: Alignment.center,
        child: dataType == index
            ? Text(
          name,
          style: TextStyle(fontWeight: FontWeight.bold),
        )
            : Text(name),
      ),
      onTap: () {
        setState(() {
          dataType = index;
          type=ctype;
          _pageController.jumpToPage(dataType);
        });
      },
    );
  }

  //获取数据
  void _getNewsInfo() async {
    var rst = await Dio().get("http://v.juhe.cn/toutiao/index?type=$type&key=63ab16553dbef3bb7ece1f420bae04a8").then((result) {
      print(result);
      //只有当前widget还在 tree中才设置值
      if (mounted) {
        setState(() {
          newsInfo = NewsInfo.fromJson(result.data);
          allData[dataType]=newsInfo.result.data;
        });
      }
    });
  }

  Widget newsPager(int index){
    var news=allData[index];
    if(news==null||news.isEmpty){
      return WidgetViews.getInstance().loading();
    }else{
      return ListView.builder(
          itemCount: news.length,
          itemBuilder: (content,i){
            return newsItem(news[i]);
          });
    }
  }

  Widget newsItem(NewContent twoLevel){
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.all(5),
        padding: EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: _constant.getItemColor(),
          borderRadius: BorderRadius.all(Radius.circular(5)),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              child: Text(twoLevel.title),
              margin: EdgeInsets.only(bottom: 10),
            ),
            Row(
              children: [
                twoLevel.thumbnail_pic_s==null?Container():Expanded(child: itemImage(twoLevel.thumbnail_pic_s)),
                twoLevel.thumbnail_pic_s02==null?Container():Expanded(child: itemImage(twoLevel.thumbnail_pic_s02)),
                twoLevel.thumbnail_pic_s03==null?Container():Expanded(child: itemImage(twoLevel.thumbnail_pic_s03)),
              ],
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: Container(
                    alignment: Alignment.bottomLeft,
                    child: Text(twoLevel.author_name),
                  ),
                ),
                Expanded(
                  child: Container(
                    alignment: Alignment.bottomRight,
                    child: Text(twoLevel.date),
                  ),
                ),
              ],
            )
          ],
        ),
      ),
      onTap: () {
        if (twoLevel.url != null && twoLevel.url.isNotEmpty) {
          Navigator.of(context).push(MaterialPageRoute(
              builder: (context) => NewDetail(
                url: twoLevel.url,
                title: twoLevel.title,
              )));
        }
      },
    );
  }

  Widget itemImage(String url){
    return Container(
      child: WidgetViews.getInstance().cachedImage(url,function: (){
        Navigator.of(context).push(MaterialPageRoute(builder: (context)=>ShowBigImage(url, false)));
      }),
      margin: EdgeInsets.all(3),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    ThemeEvent.getInstance().unregister(this);
  }
}
